package com.clb.rczx.udf;

import com.facebook.presto.spi.function.Description;
import com.facebook.presto.spi.function.ScalarFunction;
import com.facebook.presto.spi.function.SqlType;
import com.facebook.presto.spi.type.StandardTypes;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @Author: huangjing
 * @Date: 2023/08/01/下午3:25
 * @Description:
 */
public class DisambiguationUdf {
    @ScalarFunction("disambiguation")
    @Description("get disambiguation")
    @SqlType(StandardTypes.VARCHAR)
    public static Slice getDisambiguation(
            @SqlType(StandardTypes.VARCHAR) Slice name,
            @SqlType(StandardTypes.VARCHAR) Slice papers,
            @SqlType(StandardTypes.VARCHAR) Slice patents) throws Exception {
        String url = "http://10.166.166.15:8280/recluster?target_name=$name";


        String result = doPostFormData(url.replaceAll("\\$name", encodeUrl(name.toStringUtf8())), papers.toStringUtf8(), patents.toStringUtf8());
        return Slices.utf8Slice(result);
    }

    public static String encodeUrl(String url) {
        try {
            // 使用UTF-8编码对URL进行转义
            return URLEncoder.encode(url, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return url;
        }
    }

    public static String doPostFormData(String url, String papers, String patents) throws Exception {
        HttpURLConnection connection = null;
        OutputStream outputStream = null;

        try {

            URL serverUrl = new URL(url);
            connection = (HttpURLConnection) serverUrl.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);

            String boundary = "*****";
            String lineEnd = "\r\n";

            // 设置请求头
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

            outputStream = connection.getOutputStream();

            writeAttachment(outputStream, "papers", papers);
            writeAttachment(outputStream, "patents", patents);

            outputStream.write(("--" + boundary + "--" + lineEnd).getBytes());
            outputStream.flush();

            // 发送请求
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream responseStream = connection.getInputStream();
                // 使用 BufferedReader 读取响应数据
                BufferedReader reader = new BufferedReader(new InputStreamReader(responseStream));
                String line;
                StringBuilder response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                return response.toString();
            }
            throw new RuntimeException("request url" + url + "error");
        } finally {
            // 关闭连接和流
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }

    private static void writeAttachment(OutputStream outputStream, String name, String content) throws IOException {
        String boundary = "*****";
        String lineEnd = "\r\n";

        String fileName = name;
        String contentType = "application/octet-stream";

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("--").append(boundary).append(lineEnd);
        stringBuilder.append("Content-Disposition: form-data; name=\"" + fileName + "\"; filename=\"" + fileName + "\"").append(lineEnd);
        stringBuilder.append("Content-Type: " + contentType).append(lineEnd);
        stringBuilder.append(lineEnd);

        outputStream.write(stringBuilder.toString().getBytes());

        outputStream.write(content.getBytes(StandardCharsets.UTF_8));
        outputStream.write(lineEnd.getBytes());
    }


    public static void main(String[] args) throws Exception {
        DisambiguationUdf disambiguationUdf = new DisambiguationUdf();
        StringBuilder sb = new StringBuilder();
        String filePath = "E:\\conf\\name\\test.txt"; // 替换成你的文件路径

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                // 在这里对每一行内容进行处理
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        String name = "von MentzerBengt";

        String[] parma = sb.toString().split("\t");

        disambiguationUdf.getDisambiguation(Slices.utf8Slice(name), Slices.utf8Slice(parma[1]), Slices.utf8Slice(parma[2]));
    }
}
